const jwt = require('jsonwebtoken');
const Admin = require('../models/admin.model');
const { errorResponse } = require('../utils/response');
const dotenv = require('dotenv');

dotenv.config();

module.exports = async (req, res, next) => {
    try {
        // 从请求头获取token
        const token = req.headers.authorization?.split(' ')[1];

        if (!token) {
            return errorResponse(res, '未提供认证token', 401);
        }

        // 验证token
        const decoded = jwt.verify(token, process.env.JWT_SECRET);

        // 获取用户信息
        const admin = await Admin.findByPk(decoded.id);
        if (!admin) {
            return errorResponse(res, '用户不存在', 401);
        }

        // 将用户信息附加到请求对象
        req.admin = admin;
        next();
    } catch (error) {
        return errorResponse(res, '无效的token', 401);
    }
};